﻿using SwParaPlatform2.logger;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SwParaPlatform2.dlgRuleConfig
{
    public partial class dlgRuleConfigView : PageBase, IView
    {
        public event System.EventHandler OpenNodeSelected;
        public event System.EventHandler OpenRuleSetter;
        public event System.EventHandler OnClearComp;
        public event System.EventHandler OnClearRule;
        public event System.EventHandler AddRuleConfig;
        public event System.EventHandler LoadDataBtnClicked;
        public event System.EventHandler CheckDefaultSelect;
        public event System.EventHandler SaveBtnClicked;
        public event System.EventHandler DelBtnClicked;
        public event System.EventHandler ChangeBtnClicked;
        public event System.EventHandler OpenEditEquation;

        public event EventHandler<string> SelectRow;

        public event Action<string> DriveTypeChanged;
        public event Action<string> SelectElementChanged;

        private readonly ISwParaInterface _commonInterface;

        event System.EventHandler IView.NextClicked
        {
            add { base.NextClicked += value; }
            remove { base.NextClicked -= value; }
        }

        public RuleConfigDelegate mainDelegate;
        public IModel model;

        public dlgRuleConfigView():base()
        {
            InitializeComponent();
            Init();

            _commonInterface = new SwParaInterface();
            model = RuleConfigModel.Instance;
            model.ClearData(true);
            mainDelegate = new RuleConfigDelegate(this, model);
            
        }

        public void Init()
        {
            BindButton(NextPageBtn, PrevPageBtn);
            RuleConfigGrid.SelectionChanged += DataGridView_SelectionChanged;

            RuleConfigGrid.Columns["NoteCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            RuleConfigGrid.Columns["NoteCol"].Width = 80; // 设置固定宽度
        }

        public override void DoShowPage()
        {
            CheckDefaultSelect?.Invoke(this, EventArgs.Empty);
        }

        public override void Cleanup()
        {
            OpenEditEquation = null;
            DelBtnClicked = null;
            ChangeBtnClicked = null;
            SaveBtnClicked = null;
            OpenNodeSelected = null;
            OpenRuleSetter = null;
            OnClearComp = null;
            OnClearRule = null;
            AddRuleConfig = null;
            DriveTypeChanged = null;
            SelectElementChanged = null;
            SelectRow = null;

            mainDelegate.DisConnect();
            mainDelegate = null;
            
            model.ClearData(false);
        }

        public Form DoFindForm()
        {
            return this.FindForm();
        }

        public void SetSelectCompName(string sSelectCompName)
        {
            CompsInput.Text = sSelectCompName;
        }

        public void SetDriveTypeList(List<string> driveTypeList)
        {
            DriveTypeList.Items.Clear();
            foreach (var item in driveTypeList)
            {
                DriveTypeList.Items.Add(item);
            }
        }

        public void SetElementList(List<string> lElementList)
        {
            ElementList.Items.Clear();
            foreach (var item in lElementList)
            {
                ElementList.Items.Add(item);
            }
            RefreshRuleBtnState(false);
        }
        
        public void OnSetRuleData(string sRuleText)
        {
            RuleInput.Text = sRuleText;
            Debug.Print(RuleInput.Text);
        }
        
        public void RefreshAllRuleGridData(Dictionary<string, Dictionary<string, object>> dAllRuleConfigData)//遍历
        {

            RuleConfigGrid.Rows.Clear(); // 清空现有行

            int order = 1;
            try
            {
                foreach (var entry in dAllRuleConfigData)
                {
                    string element = (string)entry.Value["Element"];
                    string ruleContent = FormatRuleContent(entry.Value);
                    string sNote = "";
                    if(DataStore.Instance.dName_NoteData.TryGetValue(element, out var oNote))
                    {
                        sNote = (string)oNote;
                    }

                    RuleConfigGrid.Rows.Add(element, sNote, ruleContent);
                    order++;
                }
            }
            catch(Exception e)
            {
                Logger.Instance.Log($"加载表格失败: {this.GetHashCode()}, 异常为: {e}");
            }

        }

        // 将字典的内容格式化为字符串
        private string FormatRuleContent(Dictionary<string, object> subDict)
        {
            var ruleDict = new Dictionary<string, Dictionary<string, object>>();

            if (subDict.ContainsKey("Rule"))
            {
                if (subDict["Rule"] is Dictionary<string, object> subRuleDict)
                {
                    ruleDict = _commonInterface.ConvertToNestedDictionary(subRuleDict);
                }
                else
                {
                    ruleDict = (Dictionary<string, Dictionary<string, object>>)subDict["Rule"];
                }
                var ruleStringBuilder = new StringBuilder();
                foreach (var rule in ruleDict)
                {
                    if (rule.Value is Dictionary<string, object> ruleContent)
                    {
                        if (ruleContent.TryGetValue("sFormula", out var formulaObj) && formulaObj is string formula && !string.IsNullOrEmpty(formula))
                        {
                            if (ruleStringBuilder.Length > 0)
                            {
                                ruleStringBuilder.Append("; ");
                            }
                            ruleStringBuilder.Append($"{rule.Key}:{formula}");
                        }
                    }
                }
                return ruleStringBuilder.ToString();
            }
            return string.Empty;
        }

        public void ClearDriveType()
        {
            DriveTypeList.SelectedIndex = -1;
            // 手动调用事件处理方法
            DriveTypeList_SelectedIndexChanged(DriveTypeList, EventArgs.Empty);
        }

        public void LoadSelectDriveType(string sDriveType) 
        {
            int index = DriveTypeList.Items.IndexOf(sDriveType);
            if (index >= 0)
            {
                DriveTypeList.SelectedIndex = index; // 设置选定值
                DriveTypeList_SelectedIndexChanged(DriveTypeList, EventArgs.Empty); // 手动触发事件
            }
        }

        public void ClearElement()
        {
            ElementList.SelectedIndex = -1;
            // 手动调用事件处理方法
            ElementList_SelectedIndexChanged(ElementList, EventArgs.Empty);
        }

        public void LoadSelectElement(string sElement)
        {
            int index = ElementList.Items.IndexOf(sElement);
            if (index >= 0)
            {
                ElementList.SelectedIndex = index; // 设置选定值
                ElementList_SelectedIndexChanged(ElementList, EventArgs.Empty); // 手动触发事件
            }
        }

        public void RefreshRuleBtnState(bool bEnable)
        {
            SetRuleBtn.Enabled = bEnable;
        }

        public void RefreshEquationBtnState(bool bEnable)
        {
            EquationBtn.Enabled = bEnable;
        }

        public void RefreshTipsShow(bool bShow)
        {
            TipsLabel.Visible = bShow;
        }

        public void ClearComp()
        {
            CompsInput.Text = "";
            OnClearComp?.Invoke(this, EventArgs.Empty);
        }
        
        public void ClearRule()
        {
            RuleInput.Text = "";
            OnClearRule?.Invoke(this, EventArgs.Empty);
        }

        public void BanSelectNodeBtn()
        {
            SelectCompBtn.Enabled = false;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void SelectCompBtn_Click(object sender, EventArgs e)
        {
            OpenNodeSelected?.Invoke(this, EventArgs.Empty);
        }

        private void CompsInput_TextChanged(object sender, EventArgs e)
        {

        }

        private void DriveTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DriveTypeList.SelectedItem != null)
            {
                DriveTypeChanged?.Invoke(DriveTypeList.SelectedItem.ToString());
            }
        }

        private void ElementList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ElementList.SelectedItem != null)
            {
                SelectElementChanged?.Invoke(ElementList.SelectedItem.ToString());
            }
        }

        private void ShowRuleInput_TextChanged(object sender, EventArgs e)
        {

        }

        private void SetRuleBtn_Click(object sender, EventArgs e)
        {
            OpenRuleSetter?.Invoke(this, EventArgs.Empty);
        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            AddRuleConfig?.Invoke(this, EventArgs.Empty);
        }


        private void ReadCfgBtn_Click(object sender, EventArgs e)
        {
            LoadDataBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void DataGridView_SelectionChanged(object sender, EventArgs e)
        {

            if (RuleConfigGrid.SelectedRows.Count > 0)
            {
                var selectedRow = RuleConfigGrid.SelectedRows[0];
                // 确保“参数”列存在
                if (RuleConfigGrid.Columns["ElementCol"] != null)
                {
                    // 获取名为“参数”的列的索引
                    int columnIndex = RuleConfigGrid.Columns["ElementCol"].Index;
                    // 获取选中行中“参数”列的值
                    var cellValue = selectedRow.Cells[columnIndex].Value;
                    if (cellValue != null) // 确保单元格中的值不是null
                    {
                        var parameterValue = cellValue.ToString();
                        // 触发事件，传递获取到的参数值
                        SelectRow?.Invoke(this, parameterValue);
                    }
                }
            }
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            SaveBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            DelBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void ChangeBtn_Click(object sender, EventArgs e)
        {
            ChangeBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void EquationBtn_Click(object sender, EventArgs e)
        {
            OpenEditEquation?.Invoke(this, EventArgs.Empty);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            dlgSelectDrw mainForm = new dlgSelectDrw();
            mainForm.Show();  // 非模态显示
        }

        private void RuleConfigGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
